﻿using CodeCarvings.Piczard;
using CodeCarvings.Piczard.Filters.Watermarks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using ZSZ.AdminWeb.App_Start;
using ZSZ.AdminWeb.Models.House;
using ZSZ.Common;
using ZSZ.CommonMvc;
using ZSZ.DTO;
using ZSZ.Iservice;

namespace ZSZ.AdminWeb.Controllers
{
    public class HouseController : Controller
    {
        // GET: House
        public IHouseService HouseService { get; set; }
        public IAdminUserService AdminUserService { get; set; }
        public ICommunityService CommunityService { get; set; }
        public IAttachmentService AttachmentService { get; set; }
        public IRegionService RegionService { get; set; }
        public IIdNameService IdNameService { get; set; }
        [CheckPermission("House.Delete")]
        [HttpPost]
        public ActionResult DeltePicIds(long[] ids)
        {
            foreach (var item in ids)
            {
                HouseService.DeleteHousePic(item);
            }
            return Json(new JsonCommon { Status = "ok" });
        }
        [CheckPermission("House.Add")]
        [HttpGet]
        public ActionResult HousePicAdd(long id)
        {
            return View(id);
        }
        [CheckPermission("House.Add")]
        [HttpPost]
        public ActionResult HousePicAdd(long houseId, HttpPostedFileBase file)
        {
            string tuMd5 = CommonHelper.CalcMD5(file.InputStream);
            file.InputStream.Position = 0;
            string path = "/upload/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + tuMd5 + Path.GetExtension(file.FileName);
            string fullPath = HttpContext.Server.MapPath("~" + path);
            string suoPath = "/upload/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + tuMd5 + "_Thurm" + Path.GetExtension(file.FileName);
            string fullsuoPath = HttpContext.Server.MapPath("~" + suoPath);
            string lujing = HttpContext.Server.MapPath(DateTime.Now.ToString("~/upload/yyyy/MM/dd"));
            new FileInfo(fullPath).Directory.Create();

            //缩略图
            ImageProcessingJob jobThumb = new ImageProcessingJob();
            jobThumb.Filters.Add(new FixedResizeConstraint(300, 300));//缩略图尺寸 200*200
            jobThumb.SaveProcessedImageToFileSystem(file.InputStream, fullsuoPath);

            ImageWatermark imgWatermark = new ImageWatermark(HttpContext.Server.MapPath("~" + "/images/shuiyin.gif"));
            imgWatermark.ContentAlignment = System.Drawing.ContentAlignment.BottomRight;//水印位置
            imgWatermark.Alpha = 50;//透明度，需要水印图片是背景透明的 png 图片
            ImageProcessingJob jobNormal = new ImageProcessingJob();
            jobNormal.Filters.Add(imgWatermark);//添加水印
            jobNormal.Filters.Add(new FixedResizeConstraint(200, 200));
            jobNormal.SaveProcessedImageToFileSystem(file.InputStream, fullPath);
            HouseService.AddNewHousePic(new HousePicDTO { HouseId = houseId, Url = fullPath, ThumbUrl = fullsuoPath });
            return Json(new JsonCommon { Status = "ok" });
        }
        [CheckPermission("House.List")]
        public ActionResult HousePicList(long id)
        {
            var housePics = HouseService.GetPics(id);
            ViewBag.houseId = id;
            return View(housePics);
        }
        [CheckPermission("House.List")]
        [HttpGet]
        public ActionResult List(long typeId, int currentIndex = 1)
        {
            long? adminUserId = CommonAdmin.QuAdminUserId(HttpContext);
            long? cityId = AdminUserService.GetById((long)adminUserId).CityID;
            Session["typeId"] = typeId;
            if (cityId == null)
            {
                return Content("总部不能编辑房源");
            }
            var houses = HouseService.GetPagedData((long)cityId, typeId, 10, currentIndex);
            ViewBag.TotalCount = HouseService.GetTotalCount(typeId, (long)cityId);
            ViewBag.PageIndex = currentIndex;
            ViewBag.typeId = typeId;
            return View(houses);
        }
        [CheckPermission("House.List")]
        [HttpPost]
        public ActionResult DeletedById(long id)
        {
            HouseService.MarkDeleted(id);
            return Json(new JsonCommon { Status = "ok" });
        }
        [CheckPermission("House.List")]
        [HttpPost]
        public ActionResult DeleteByIds(long[] houseIds)
        {
            foreach (var item in houseIds)
            {
                HouseService.MarkDeleted(item);
            }
            return Json(new JsonCommon { Status = "ok" });
        }
        [CheckPermission("House.Add")]
        [HttpGet]
        public ActionResult Add()
        {
            long cityId = 3;
            ViewBag.Regions = RegionService.GetAll(cityId);
            ViewBag.FangXing = IdNameService.GetAll("房屋户型");
            ViewBag.Zhuang = IdNameService.GetAll("房屋状态");
            ViewBag.ZhuangZhuang = IdNameService.GetAll("装修状态");
            ViewBag.Attachmentes = AttachmentService.GetAll();
            ViewBag.TypeId = Session["typeId"];
            return View();
        }
        [HttpPost]
        public ActionResult XiaoQuByRegionId(long id)
        {
            var xiaoqus = CommunityService.GetByRegionId(id);
            return Json(xiaoqus);
        }
        [CheckPermission("House.Add")]
        [HttpPost]
        public ActionResult Add(HouseAddPostModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new JsonCommon { Status = "err", ErrorMsg = ModelStateConsole.GetErrorMsg(ModelState) });
            }
            HouseDTO dto = new HouseDTO();
            dto.Address = model.Address;
            dto.Area = model.Area;
            dto.AttachmentIds = model.AttachmentIds;
            dto.CheckInDateTime = model.CheckInDateTime;
            dto.CommunityId = model.CommunityId;
            dto.DecorateStatusId = model.DecorateStatusId;
            dto.Description = model.Description;
            dto.Direction = model.Description;
            dto.LookableDateTime = model.LookableDateTime;
            dto.MonthRent = model.MonthRent;
            dto.OwnerName = model.OwnerName;
            dto.OwnerPhoneNum = model.OwnerPhoneNum;
            dto.RegionId = model.RegionId;
            dto.RoomTypeId = model.RoomTypeId;
            dto.StatusId = model.StatusId;
            dto.TypeId = model.TypeId;
            dto.TotalFloorCount = model.TotalFloorCount;
            dto.FloorIndex = model.FloorIndex;
            HouseService.AddNew(dto);
            return Json(new JsonCommon { Status = "ok" });
        }
        [CheckPermission("House.Edit")]
        [HttpGet]
        public ActionResult Edit(long id)
        {
            long cityId = 3;
            HouseEditGet model = new HouseEditGet();
            model.House = HouseService.GetById(id);
            model.Regions = RegionService.GetAll(cityId);
            model.FangXing = IdNameService.GetAll("房屋户型");
            model.Zhuang = IdNameService.GetAll("房屋状态");
            model.ZhuangZhuang = IdNameService.GetAll("装修状态");
            model.Attachmentes = AttachmentService.GetAll();
            model.TypeId = (long)Session["typeId"];
            return View(model);
        }
        [CheckPermission("House.Edit")]
        [HttpPost]
        public ActionResult Edit(HouseEditPost model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new JsonCommon { Status = "err", ErrorMsg = ModelStateConsole.GetErrorMsg(ModelState) });
            }
            HouseDTO dto = new HouseDTO();
            dto.Id = model.HouseId;
            dto.Address = model.Address;
            dto.Area = model.Area;
            dto.AttachmentIds = model.AttachmentIds;
            dto.CheckInDateTime = model.CheckInDateTime;
            dto.CommunityId = model.CommunityId;
            dto.DecorateStatusId = model.DecorateStatusId;
            dto.Description = model.Description;
            dto.Direction = model.Description;
            dto.LookableDateTime = model.LookableDateTime;
            dto.MonthRent = model.MonthRent;
            dto.OwnerName = model.OwnerName;
            dto.OwnerPhoneNum = model.OwnerPhoneNum;
            dto.RegionId = model.RegionId;
            dto.RoomTypeId = model.RoomTypeId;
            dto.StatusId = model.StatusId;
            dto.TypeId = model.TypeId;
            dto.TotalFloorCount = model.TotalFloorCount;
            dto.FloorIndex = model.FloorIndex;
            HouseService.Update(dto);
            return Json(new JsonCommon { Status = "ok" });
        }
    }
}